//
//  AddBankViewController.m
//  wangzhe
//
//  Created by 李 佳伟 on 2017/10/19.
//  Copyright © 2017年 李 佳伟. All rights reserved.
//

#import "AddBankViewController.h"
#import "RegisterVIew.h"
#import "JTCSM.h"
#import "GetInfoClass.h"
#import "BRStringPickerView.h"
#import "WebViewController.h"
#import "TrueNameViewController.h"

#define KTop 10
#define KWidthOfRegister 50
@interface AddBankViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
{
    NSArray *imageNameArray;
    NSArray *placeholderArray;
    NSMutableArray* _areaArray;
    RegisterVIew * registerV;
    UIButton *getKeyBtn;
    NSTimer* _timer1;
    NSTimer* _timer2;
    NSInteger count ;
    UIButton *radioBtn;
    BOOL isSelector;
    NSMutableArray *textFieldArray;
    int idx ;
    UIView *backView;
    
    NSString *truename ;
    NSString *card_id ;
    NSString *card_bank ;
    NSString *cvn2 ;
    NSString *youxiaodata;
    NSString *bank_name ;
    NSString *zhangdan ;
    NSString *huankan ;
    NSString *phonenumber;
    NSString *code ;
    NSString *quota;
    NSString *bank_id;
    NSString *is_verified;

    
}

@end

@implementation AddBankViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =RGBACOLOR(241, 241, 241, 1);
    self.navigationController.navigationBar.hidden = NO;
    textFieldArray = [NSMutableArray arrayWithCapacity:2];
    //设置barbuttonitem
    leftBarButtonItems_rightBarButtonItems *leftbtn = KCUSTOMNAVIGSTION_ALLOC;
    self.navigationItem.leftBarButtonItem = [leftbtn setBarButtonItemsImageName:@"fanhui.png" frame:KLeftBarButtonItemFrame_image target:self SEL:@selector(gotBack)];
   
    //回收键盘
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeKeyBoard)];
    [self.view addGestureRecognizer:tap];
    [self layoutView];
    [[GetInfoClass shareSingle] getinfo];

    [GetInfoClass shareSingle].myblock = ^(UserInfoModel *Model) {
    
        RegisterVIew *one = [backView viewWithTag:1000];
        one.textField.text = Model.truename;
        RegisterVIew *two = [backView viewWithTag:1001];
        two.textField.text = Model.id_card;
        is_verified = Model.is_verified;
        
//        if ([is_verified isEqualToString:@"0"]) {
//            [df showAlertWithTitle:@"还未实名认证" message:nil btn1:@"去认证" btn2:@"考虑一下" btn3:nil delegate:self tag:123];
//            
//        }else if ([is_verified isEqualToString:@"1"]) {
//            
//        } else{
//            [df showAlertWithTitle:@"请耐心等待！" message:@"实名认证审核中" btn1:@"知道了" btn2:nil btn3:nil delegate:self tag:124];
//            [self gotBack];
//        }
    
    };

    // Do any additional setup after loading the view.
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag == KAlertVTag+123){
        if (buttonIndex == 0) {
            [self gotoTrueNameVC];
        }else{
            [self gotBack];
        }
    }else  if(alertView.tag == KAlertVTag+123){
        [self gotBack];
    }
}

- (void)gotoTrueNameVC{
    TrueNameViewController *vc = [[TrueNameViewController alloc]init];
    vc.nameTitle = @"实名认证";
    [self.navigationController pushViewController:vc animated:NO];
    
}
- (void)gotBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)layoutView{
    
    backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,20+KWidthOfRegister*8)];
    backView.userInteractionEnabled = YES;
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];
    idx = 0;
    CGFloat imagesize = 15;
    imageNameArray =@[@"姓名",@"信用卡号",@"发卡银行",@"CVN2",@"有效期",@"手机号码",@"验证码",@"每月还款日"];
    placeholderArray=@[@"",@"输入信用卡卡号",@"开户行",@"银行卡背后三位数",@"有效期（月年）",@"银行预留手机号",@"输入验证码",@"请选择"];
    [df newlineViewWithHeightofTop:10 superView:backView spacing:0 color:RGBACOLOR(241, 241, 241, 1) lineHeight:10];
    for (int i = 0; i < placeholderArray.count; i++) {
        registerV = [[RegisterVIew alloc]initWithFrame:CGRectMake(0,10+i*KWidthOfRegister+(i!=0?10:0), self.view.frame.size.width, KWidthOfRegister) labeTtext:nil placeholder:placeholderArray[i]];
        registerV.userInteractionEnabled =YES;
        registerV.textField.textAlignment= NSTextAlignmentLeft;
        registerV.textField.tag = 100+i;
        registerV.tag = 1000+i;
        [registerV.textField setValue:RGBACOLOR(120, 130, 140,1) forKeyPath:@"_placeholderLabel.textColor"];
        registerV.label.textAlignment = NSTextAlignmentLeft;
        [backView addSubview:registerV];
        [textFieldArray addObject:registerV];
        [self addImageWith:registerV];
        registerV.textField.delegate = self;
        [registerV.textField addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];
        if (i ==0) {
            registerV.textField.enabled = NO;
            [df newlineViewWithHeightofTop:20+KWidthOfRegister superView:backView spacing:0 color:RGBACOLOR(241, 241, 241, 1) lineHeight:10];
        }else{
            [self addLineWith:registerV];

        }
        if (i ==placeholderArray.count-2) {
            CGFloat btnHeight = 30;
            getKeyBtn = [UIButton initWithFrame:CGRectMake(KCONTROLLERWith-KBtnWidth-13, registerV.frame.origin.y+(KWidthOfRegister-btnHeight)/2, KBtnWidth-5, btnHeight) backgrandColor:nil titleColor:RGBACOLOR(89, 89, 89, 1 ) title:@"获取验证码" titleFont:12];
            [getKeyBtn addTarget:self action:@selector(getToKey) forControlEvents:UIControlEventTouchUpInside];

            [backView addSubview:getKeyBtn];
            [df layerWithView:getKeyBtn radius:15 width:1 color:KZhuTiRGB];
            registerV.textField.frame = CGRectMake(registerV.textField.frame.origin.x, registerV.textField.frame.origin.y, registerV.textField.frame.size.width-KBtnWidth-10, registerV.textField.frame.size.height);
        }
        if ( i == 2 || i == 7) {
            registerV.textField.enabled = NO;
            
            UIImageView *imageView  = [[UIImageView alloc]initWithFrame:CGRectMake(KCONTROLLERWith-imagesize-20,  (registerV.frame.size.height-imagesize)/2, imagesize, imagesize)];
            imageView.image = [UIImage imageNamed:@"myFanhui.png"];
            [registerV addSubview:imageView];
    
            registerV.textField.frame = CGRectMake(registerV.textField.frame.origin.x, registerV.textField.frame.origin.y, registerV.textField.frame.size.width-imagesize-15, registerV.textField.frame.size.height);
            registerV.textField.textAlignment= NSTextAlignmentRight;

            if (i  != 2) {
                [df addTapGestureRecognizerWithTarget:self action:@selector(xuanzeRiqi:) andaddView:registerV];
            }
        }
        
    }
    NSString *string = @"同意《信用卡还款服务协议》";
    float font = 12;
    CGFloat labelHeight = 30;
    CGRect rect = [df labelHeightWithContent:string height:labelHeight font:font];
    CGFloat btnimagesize = 20;
    CGFloat changesize = 10;
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(20, KVIEW_Y(registerV)+20, rect.size.width+btnimagesize+changesize, labelHeight);
    [leftButton setImage:[UIImage imageNamed:@"btn_02.png"] forState:UIControlStateNormal];
    [leftButton setImage:[UIImage imageNamed:@"btn_01.png"] forState:UIControlStateSelected];
    
    [leftButton addTarget:self  action:@selector(saveloginInfo:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setTitle:string forState:UIControlStateNormal];
    [leftButton.titleLabel setFont:[UIFont systemFontOfSize:font]];
    //        image的位置大小调整
    leftButton.imageEdgeInsets = UIEdgeInsetsMake(7.5, 0, 7.5, rect.size.width+changesize);
    //        title的位置大小调整
    leftButton.titleEdgeInsets = UIEdgeInsetsMake(0, -btnimagesize+changesize, 0, 0);
    [leftButton setTitleColor:RGBACOLOR(100, 100, 100, 1) forState:UIControlStateNormal];
    [self.view addSubview:leftButton];
    
    
    UIButton *tijiaobutton = [UIButton buttonWithType:UIButtonTypeCustom];
    tijiaobutton.frame = CGRectMake(25, KVIEW_Y(leftButton)+20, KCONTROLLERWith-40, 50);
    [tijiaobutton addTarget:self action:@selector(tijiao) forControlEvents:UIControlEventTouchUpInside];
    [df layerWithView:tijiaobutton radius:25 width:0 color:nil];
    tijiaobutton.backgroundColor = KZhuTiRGB;
    [tijiaobutton setTitleColor:RGBACOLOR(51, 51, 51, 1) forState:UIControlStateNormal];
    [tijiaobutton setTitle:@"立即绑定" forState:UIControlStateNormal];
    [self.view addSubview:tijiaobutton];

    
}

- (void)saveloginInfo:(UIButton *)sender{
    
}
- (void)xuanzeRiqi:(UITapGestureRecognizer *)tap{
    
    RegisterVIew *view = (RegisterVIew *)[tap view];
    // 自定义单列字符串
    [BRStringPickerView showStringPickerWithTitle:@"" dataSource:[self getRiqi] defaultSelValue:@"15日" isAutoSelect:YES resultBlock:^(id selectValue) {
        view.textField.text = selectValue;
        if (view.tag == 1006) {
            zhangdan = [selectValue stringByReplacingOccurrencesOfString:@"日" withString:@""];
        }
        if (view.tag == 1007) {
            huankan = [selectValue stringByReplacingOccurrencesOfString:@"日" withString:@""];
        }
    }];
}
- (NSMutableArray *)getRiqi{
    NSMutableArray *data = [NSMutableArray array];
    for (int i =1; i<29; i++) {
        [data addObject:[NSString stringWithFormat:@"%d日",i]];
    }
    return data;
}
- (void)tijiao{
    [self.view endEditing:YES];
    
   
//    CreditCard/create
//    "bank_card" : "1234","bank_name" : "1234","bank_tel" : "15698863741","code" : "1234","period" : "12/20","quota" : "1000","bill_date" : "25","repay_date" : "15","cvn2" : "012"
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
    LoadData *request = [[LoadData alloc]init];
    [dict setObject:KTokenString==nil?@"":KTokenString forKey:@"token"];
    [dict setObject:card_bank==nil?@"":card_bank forKey:@"bank_card"];
    [dict setObject:bank_name==nil?@"":bank_name forKey:@"bank_name"];
    [dict setObject:phonenumber==nil?@"":phonenumber forKey:@"bank_tel"];
    [dict setObject:youxiaodata==nil?@"":youxiaodata forKey:@"period"];
    [dict setObject:code==nil?@"":code forKey:@"code"];
    [dict setObject:zhangdan==nil?@"":zhangdan forKey:@"bill_date"];
    [dict setObject:huankan==nil?@"":huankan forKey:@"repay_date"];
    [dict setObject:phonenumber==nil?@"":phonenumber forKey:@"mobile"];
    [dict setObject:cvn2==nil?@"":cvn2 forKey:@"cvn2"];
    [dict setObject:quota==nil?@"":quota forKey:@"quota"];
    [dict setObject:bank_id==nil?@"":bank_id forKey:@"bank_id"];

    NSLog(@"%@",dict);
    
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"CreditCard/create") withDict:dict superView:self.view isAddtag:YES  Block:^(id result) {
        
        
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
        if ([isreturn isEqualToString:@"1"]) {
//            NSDictionary *dict = KResultOfKey(@"data");
//            if ([[dict objectForKey:@"source"] isEqualToString:@""] || [dict objectForKey:@"source"]==nil) {
                [self gotBack];
//            }else{
////               [dict objectForKey:@"source"]
//                WebViewController *vc = [[WebViewController alloc]init];
//                vc.titleName = @"王者管家";
//                vc.urlStr = [dict objectForKey:@"source"];
//                [self.navigationController pushViewController:vc animated:YES];
//            }
        }else{
            [df showAlertWithTitle:[result objectForKey:@"msg"] message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
            //            [self theRequestOftuwenyanzhengma];
        }
        
    }];
    
    
}
#pragma mark --重新获取验证码
- (void)getTheCode{
    [self.view endEditing:YES];
    
    LoadData *request = [[LoadData alloc]init];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
    [dict setObject:@"credit_card" forKey:@"do"];
    NSLog(@"%@",phonenumber);
    [dict setObject:phonenumber forKey:@"mobile"];
    [dict setObject:KTokenString forKey:@"token"];
    
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"User/smsverified") withDict:dict superView:self.view isAddtag:NO Block:^(id result) {
        
        [self gettime];
        
        NSLog(@"*********************%@",result);
        if (result == nil ) {
            [df showAlertWithTitle:@"获取验证码失败" message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
            return ;
        }
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"result"]];
        if ([isreturn isEqualToString:@"1"]) {
            [df showAlertWithTitle:[result objectForKey:@"msg"] message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
        }else{
            [df showAlertWithTitle:[result objectForKey:@"msg"] message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
        }
        [getKeyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        
    }];
    
    
}
- (void)getToKey{
    
    [self getTheCode];
    
}



#pragma mark --添加灰线条
-(void)addImageWith:(UIView *)fatherview{
    
    UILabel *lable =[[UILabel alloc] initWithFrame:CGRectMake(20,  0, 77, KWidthOfRegister-1.5)];
    [lable setText:imageNameArray[idx++]];
    lable.textAlignment=YES;
    lable.textAlignment = NSTextAlignmentLeft;
    lable.backgroundColor =[UIColor whiteColor];
    lable.font =[UIFont fontWithName:@"Arial" size:15.0];
    [fatherview addSubview:lable];
    
    
}
- (void)addLineWith:(UIView *)fatherview{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(20, fatherview.frame.size.height-1.5, KCONTROLLERWith-40, 1.5)];
    view.backgroundColor = RGBACOLOR(226, 227, 228,1);
    [fatherview addSubview:view];
    
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder] ;
    return YES;
}
- (void)removeKeyBoard{
    [self.view endEditing:YES];
}
#pragma mark --定时器
- (void)gettime{
    [_timer2 invalidate];
    [_timer1 invalidate];
    
    count = 0;
    
    NSTimer* timer=[NSTimer scheduledTimerWithTimeInterval:60
                                                    target:self
                                                  selector:@selector(showRepeatButton)
                                                  userInfo:nil
                                                   repeats:YES];
    
    NSTimer* timer2=[NSTimer scheduledTimerWithTimeInterval:1
                                                     target:self
                                                   selector:@selector(updateTime)
                                                   userInfo:nil
                                                    repeats:YES];
    _timer1=timer;
    _timer2=timer2;
    
}
-(void)updateTime{
    count++;
    if (count>60)
    {
        [_timer2 invalidate];
        return;
    }
    NSString *timeStr=[NSString stringWithFormat:@"%lus重新获取",(long)60-count];
    [getKeyBtn setTitle:timeStr forState:UIControlStateNormal];
    if(count == 60){
        [getKeyBtn setTitle:@"重新获取" forState:UIControlStateNormal];
    }
    
}
-(void)showRepeatButton{
    
    [_timer1 invalidate];
    return;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    if (textField.tag == 102) {
        if ([toBeString length] > 15) {
            [self therequestwithBankNumber:toBeString];
        }
        
    }
    
    return YES;
}
- (void)therequestwithBankNumber:(NSString *)bankNum{
    LoadData *request = [[LoadData alloc]init];
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"User/getBankInfo") withDict:@{@"token":KTokenString,@"bank_card":bankNum} superView:self.view isAddtag:NO  Block:^(id result) {
        
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
        if ([isreturn isEqualToString:@"1"]) {
            
            RegisterVIew *view = [backView viewWithTag:1005];
            NSDictionary *dict = KResultOfKey(@"data");
            view.textField.text = [dict objectForKey:@"bank_name"];
            bank_name = view.textField.text;
            bank_id = [dict objectForKey:@"bank_id"];
            
        }
    }];
}

#pragma mark 监听textfield 的变化
- (void)valueChanged:(UITextField *)textfield{
    
    switch (textfield.tag) {
        case 100:
            truename = textfield.text;
            break;
        case 101:
            card_id = textfield.text;
            break;
        case 102:
            card_bank = textfield.text;
            break;
        case 103:
            cvn2 = textfield.text;
            break;
        case 104:
            youxiaodata = textfield.text;
            break;
        case 105:
            bank_name = textfield.text;
            break;
        case 106:
            zhangdan = textfield.text;
            break;
        case 107:
            huankan = textfield.text;
            break;
        case 108:
            phonenumber = textfield.text;
            break;
        case 109:
            code = textfield.text;
            break;
            
        default:
            break;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
